package com.pateo.bjev.contacts.adapter;

import android.content.Context;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.pateo.bjev.contacts.R;
import com.pateo.bjev.contacts.callback.ItemClickCallback;
import com.pateo.bjev.contacts.utils.ContactSearchUtils;

import java.util.LinkedList;
import java.util.List;

/**
 * Created by pateo on 17-5-11.
 */

public class SearchNumAdapter extends RecyclerView.Adapter<SearchNumAdapter.ViewHolder> {

    Context mContext;
    List<ContactSearchUtils.SearchNumResult> resultList = new LinkedList<>();
    String matcher;

    ItemClickCallback<ContactSearchUtils.SearchNumResult> itemClickCallback;

    public SearchNumAdapter(Context context,String matcher,List<ContactSearchUtils.SearchNumResult> resultList){
        this.matcher = matcher;
        this.mContext = context;
        this.resultList = resultList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.search_list_item,parent,false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        ContactSearchUtils.SearchNumResult searchNumResult = resultList.get(position);
        ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);
        SpannableString spannableString = new SpannableString(searchNumResult.getNumber());

        int start = searchNumResult.getNumber().indexOf(matcher);
        int lenght = matcher.length();
        spannableString.setSpan(span,start,start+lenght, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

        holder.name.setText(searchNumResult.getName());
        holder.number.setText(spannableString);
    }

    @Override
    public int getItemCount() {
        return resultList.size();
    }

    /**
     * 设置搜索匹配号码结果的list item点击回调
     * @param callback
     */
    public void setItemClickCallback(ItemClickCallback<ContactSearchUtils.SearchNumResult> callback){
        this.itemClickCallback = callback;
    }

    class ViewHolder extends RecyclerView.ViewHolder{

        TextView name;
        TextView number;

        public ViewHolder(View itemView) {
            super(itemView);
            name = (TextView) itemView.findViewById(R.id.contact_name);
            number = (TextView) itemView.findViewById(R.id.contact_num);
        }
    }
}
